import { Avatar, Icon, Menu, Spin } from 'antd';
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { getCookie } from '@/utils/utils';
import styles from './index.less';

import HeaderDropdown from '../HeaderDropdown';

class AvatarDropdown extends React.Component {
  onMenuClick = event => {
    const { dispatch } = this.props;
    const { key } = event;

    if (key === 'logout') {
      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }
    } else if (key === 'setting') {
      if (dispatch) {
        dispatch({
          type: 'global/changeState',
          payload: {
            visible: '修改密码'
          }
        });
      }
    }

    return;
  };

  render() {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const name = getCookie('displayName');

    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key='center'>
            <Icon type='user' />
            <FormattedMessage id='menu.account.center' defaultMessage='account center' />
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key='settings'>
            <Icon type='setting' />
            <FormattedMessage id='menu.account.settings' defaultMessage='account settings' />
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}

        <Menu.Item key='setting'>
          <Icon type='setting' />
          修改密码
        </Menu.Item>
        <Menu.Item key='logout'>
          <Icon type='logout' />
          退出登录
        </Menu.Item>
      </Menu>
    );
    return name ? (
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size='small' className={styles.avatar} src='/img/default.png' alt='avatar' />
          <span className={styles.name}>{name}</span>
        </span>
      </HeaderDropdown>
    ) : (
        <Spin
          size='small'
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
